/**
 * 利润表
 */

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:zywz/config/app_colors.dart';

import '../../api/api_client.dart';
import '../../bloc/report/report_bloc.dart';
import '../../bloc/report/report_data.dart';
import '../../bloc/report/report_event.dart';
import '../../dialog/showBtm.dart';
import '../../widgets/EmptyPlaceholder.dart';

class IncomeStatement extends StatelessWidget {
  const IncomeStatement({super.key});
  @override
  Widget build(BuildContext context) {
    return BlocProvider<ReportBloc>(
      create: (context) => ReportBloc(apiClient: ApiClient.instance),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          scaffoldBackgroundColor: const Color(0xFFF7F9FC), // 背景色
          appBarTheme: const AppBarTheme(
            backgroundColor: Colors.white,
            elevation: 0,
            centerTitle: true,
            titleTextStyle: TextStyle(
              color: Colors.black,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        home: ProfitTablePage(),
      ),
    );
  }
}

class ProfitTablePage extends StatefulWidget {
  @override
  State<ProfitTablePage> createState() => _ProfitTablePageState();
}

class _ProfitTablePageState extends State<ProfitTablePage> {


  int getCurrentQuarter() {
    final now = DateTime.now();
    return (now.month - 1) ~/ 3 + 1;
  }

  // 或者更详细的方法
  String getCurrentQuarterString() {
    final now = DateTime.now();
    final quarter = (now.month - 1) ~/ 3 + 1;
    switch (quarter) {
      case 1:
        return '第一季度';
      case 2:
        return '第二季度';
      case 3:
        return '第三季度';
      case 4:
        return '第四季度';
      default:
        return '第一季度'; // 默认值
    }
  }
  // 或者更详细的方法
  String getCurrentJd(int caseOp) {
    switch (caseOp) {
      case 1:
        return '第一季度';
      case 2:
        return '第二季度';
      case 3:
        return '第三季度';
      case 4:
        return '第四季度';
      default:
        return '第一季度'; // 默认值
    }
  }


  var jidu = '第一季度';
  var jiduIndex = 0;
  var yearIndex = 0;
  var titleShow ="(2025) 第一季度";

  final List<String> jiduStart = ['01', '03', '06', '09'];
  final List<String> jiduEnd = ['03', '06', '09', '12'];

  @override
  void initState() {
    super.initState();


    var selectedYear = DateTime.now().year;
    yearIndex = 0;
    jidu = getCurrentQuarterString();
    jiduIndex = getCurrentQuarter()-1;
    titleShow = "($selectedYear) $jidu";

    context.read<ReportBloc>().add(LoadReportIncomeData( "$selectedYear${jiduStart[jiduIndex]}", "$selectedYear${jiduEnd[jiduIndex]}"));
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   backgroundColor: AppColors.primaryColor,
      //   leading: IconButton(
      //     icon: Icon(Icons.arrow_back, color: AppColors.textWhite),
      //     onPressed: () =>context.pop(),
      //   ),
      //   centerTitle: true,
      //   title: Text("利润表", style: TextStyle(color: AppColors.textWhite, fontSize: 18, fontWeight: FontWeight.bold)),
      // ),
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black, size: 20),
          onPressed: () {
            // 返回上一页的逻辑
            context.pop();
            // context.push('/WheelPickerExample');
          },
        ),
        title: const Text('利润表'),
      ),
      body: Column(
        children: [
          // 时间选择器区域
          _buildTimeSelector(context),
          // 纳税查看Banner
          // _buildBanner(context),
          // const SizedBox(height: 10),
          // // 纳税列表
          Expanded(child: _buildTaxList()),
        ],
      ),
    );
  }

  Widget _buildTaxList() {
    return BlocConsumer<ReportBloc, ReportState>(
        buildWhen: (previous, current) {
          if (current is ReportIncomeReportSuccess) {
            return true;
          }
          return false;
        },
        listener: (context, state) {
          if (state is ReportLoadFailure) {

          }
        },
        builder: (context, state) {
          if (state is ReportIncomeReportSuccess) {
            var mSize = state.reportData.length;
            if(mSize == 0){
              return Center(child: EmptyPlaceholder(message: '暂无利润数据'));
            }
            return SingleChildScrollView(
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 0.0),
                padding: const EdgeInsets.all(0.0),
                decoration: BoxDecoration(
                  color: Colors.white,

                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.1),
                      spreadRadius: 1,
                      blurRadius: 5,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                child: Column(
                  // children: taxItems.map((item) => TaxListItem(item: item)).toList(),
                  // children:[...(state.map((item) => TaxListItem(keyItem: '1', valueItem: '2')).toList())],
                  children: state.reportData.map((entry) =>
                      InComeItem( data: entry ,)).toList(), // 注意这里需要 toList()
                  // children: [],
                ),
              ),
            );
          } else {
            return Container();
          }
        });
  }

  // 构建时间选择器
  Widget _buildTimeSelector(BuildContext context) {
    return Container(

      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: () async {
          var dataMap= await  showSlectSheet1(
            context,
            indexYear: yearIndex,
            jiduItem: jiduIndex,
            callBack: (year, jidu) {
              print('$year $jidu');
              var selectedYear = DateTime.now().year;
              setState(() {
                yearIndex = year;
                jiduIndex = jidu;

                titleShow = "(${selectedYear - year}) ${getCurrentJd(jidu+1)}";
              });

              context.read<ReportBloc>().add(LoadReportIncomeData( "${selectedYear - yearIndex}${jiduStart[jiduIndex]}", "${selectedYear - yearIndex}${jiduEnd[jiduIndex]}"));

            },
          );

          print("dataMap $dataMap");

          // showBottomSheet(
          //   context,
          //   title: '选择时间',
          //   items: ['2025年第一季度', '2025年第二季度', '2025年第三季度', '2025年第四季度'],
          //   onTap: (index) {
          //     // 处理选择的时间
          //   },
          // );
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              titleShow,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Icon(Icons.arrow_drop_down),
          ],
        ),
      ),
    );
  }

}

// 可复用的列表项组件
class InComeItem extends StatelessWidget {
  final Map<String,dynamic> data;
  const InComeItem({super.key, required this.data});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      mainAxisSize:MainAxisSize.max ,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [

        SizedBox(height: 6,
          child: Container(
            height: 1,
            color: Colors.grey[200],
          ),
        ),
        Container(
            padding: EdgeInsets.only(top: 8,bottom: 8,left: 16,right: 16),
            child: Text(data?['name']??'',style: TextStyle(color: Color(0xFF4DD0E1),fontSize: 18),)),

        Divider(
          height: 0.0,      // 分隔线高度为20像素
          thickness: 2.0,    // 分隔线厚度为2像素
          color: Colors.grey[200],),
        Container(
          padding: EdgeInsets.only(top: 8,bottom: 8,left: 16,right: 16),
          child: Row(children: [
            Expanded(child: Text(data?['monthName']??'')),
            Text(data?['monthBalance']??''),
          ],),
        ),
        Divider(
          height: 0.0,      // 分隔线高度为20像素
          thickness: 2.0,    // 分隔线厚度为2像素
          color: Colors.grey[200],),
        Container(
          padding: EdgeInsets.only(top: 8,bottom: 8,left: 16,right: 16),
          child: Row(children: [
            Expanded(child: Text(data?['yearName']??'')),
            Text(data?['yearBalance']??''),
          ],),
        )
      ],
    );
  }
}
